<template>
  <view class="container">
    <view class="address_container">
      <block v-if="address">
        <view
          class="address"
          @click="chooseAddress"
        >{{address.provinceName}}{{address.cityName}}{{address.countyName}}{{address.detailInfo}}</view>
        <view class="user_info">
          <view class="name">{{address.userName}}</view>
          <view class="phone">{{formatPhone(address && address.telNumber)}}</view>
        </view>
      </block>
      <block v-else>
        <view v-if="canReadAdress" class="chooseAddress" @tap="chooseAddress">选择收货地址</view>
        <button
          class="chooseAddress"
          v-else
          open-type="openSetting"
          @opensetting="settingCallback"
        >授权读取地址</button>
      </block>
    </view>
    <view class="products_container">
      <view class="container_title">已选商品</view>
      <view class="product" v-for="product in products" :key="product.goods_id">
        <product
          :goods_count="product.counter"
          :goods_small_logo="product.goods_small_logo"
          :goods_id="product.goods_id"
          :goods_name="product.goods_name"
          :goods_price="product.goods_price"
        />
      </view>
    </view>
    <view class="total">
      <view class="price_container">
        <text class="title">合计:</text>
        <text class="price">¥{{totalPrice}}</text>
      </view>
      <view @click="pay" class="goToPay" :class="address ? '': 'disable'">去支付（{{totalCount}}）</view>
    </view>
  </view>
</template>

<script>
import product from "../../components/Product";
import http from "../utils/http";

export default {
  data() {
    return {
      canReadAdress: true, // 是否可以读取用户地址
      address: null, // 用户收获地址
      products: [], // 结算的商品
      totalCount: 0 // 总数
    };
  },
  computed: {
    totalPrice() {
      // 计算总价
      let totalPrice = 0;
      let totalCount = 0;
      this.products &&
        this.products.forEach(product => {
          totalPrice += product.counter * product.goods_price;
          totalCount += product.counter;
        });
      this.totalCount = totalCount;
      return totalPrice;
    }
  },
  async onLoad() {
    const [error, res] = await uni.getSetting();
    // 获取结算商品
    this.getProducts();
    this.initAddress();
  },
  components: {
    product
  },
  methods: {
    // 获取结算商品
    getProducts() {
      // 获取购物车商品
      const cart = uni.getStorageSync("cart");
      // 筛选已经勾选的商品
      this.products = cart.filter(product => {
        return product.checked;
      });
    },
    // 选择收货地址
    chooseAddress() {
      uni.chooseAddress({
        success: e => {
          // 用户确认选择地址，进入success回调
          // 将用户信息保存到data中
          this.address = e;
          // console.log(e);
          this.saveAdress(e);
        },
        fail(e) {
          // 用户取消选择地址，进入fail方法回调
          // console.log(e, "用户取消选择");
          // 表示没有授权
          if (e.errMsg === "chooseAddress:fail auth deny") {
            this.canReadAdress = false;
          }
        }
      });
    },
    formatPhone(phone) {
      if (phone) {
        const startStr = phone.substr(0, 4);
        const endStr = phone.substr(-3, 3);
        return `${startStr}****${endStr}`;
      }
    },
    settingCallback(e) {
      // console.log(e);
      this.canReadAdress = e.detail.authSetting["scope.address"];
    },
    saveAdress(e) {
      uni.setStorageSync("address", e);
    },
    // 读取本地缓存，用于回显地址
    initAddress() {
      this.address = uni.getStorageSync("address");
    },
    async pay() {
      // 收货地址
      const { provinceName, cityName, countyName, detailInfo } = this.address;
      const consignee_addr = `${provinceName}${cityName}${countyName}${detailInfo}`;
      const goods = this.products.map(product => {
        return {
          goods_id: product.goods_id,
          goods_number: product.counter,
          goods_price: product.goods_price
        };
      });
      // 获取token
      const token = uni.getStorageSync("token");
      // 生成订单
      const orderRes = await http.post(
        "/my/orders/create",
        { order_price: this.totalPrice, consignee_addr, goods },
        token
      );
      console.log(orderRes);
      // 生成预支付
      const prePayRes = await http.post(
        "/my/orders/req_unifiedorder",
        { order_number: orderRes.order_number },
        token
      );
      // 调用本地支付接口，发起支付
      console.log(prePayRes);
      const { nonceStr, paySign, signType, timeStamp } = prePayRes.pay;
      console.log(nonceStr, paySign, signType);
      const [error, payRes] = await uni.requestPayment({
        nonceStr,
        package: prePayRes.pay.package,
        paySign,
        signType,
        timeStamp
      });
      // 提醒用户支付成功，跳转到订单查询页面
      console.log(error, payRes);
      if (!error) {
        uni.showToast({
          title: "支付成功！"
        });
        setTimeout(() => {
          uni.redirectTo({
            url: "/pages/order/index"
          });
        }, 2000);
        this.clearHasPayProduct();
      }
    },
    // 清除购物车已经结算的商品
    clearHasPayProduct() {
      const cart = uni.getStorageSync("cart");
      // 获取购物车中选中状态为未选的商品
      const newCart = cart.filter(product => {
        return !product.checked;
      });
      uni.setStorageSync("cart", newCart);
    }
  }
};
</script>
<style lang="less">
page {
  background: #fafafa;
}
.container {
  .address_container {
    padding: 16rpx 29rpx;
    margin: 20rpx;
    border-radius: 5rpx;
    background-color: #fff;
    min-height: 137rpx;
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .address {
      font-size: 30rpx;
      font-weight: bold;
      color: #434343;
      margin-bottom: 18rpx;
    }
    .user_info {
      display: flex;
      font-size: 26rpx;
      color: #434343;
      .name {
        margin-right: 20rpx;
      }
    }
    .chooseAddress {
      // 清除button默认样式
      button {
        padding: 0;
        line-height: 1;
        background: none;
      }
      button:after {
        border: 0;
      }
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translateX(-50%) translateY(-50%);
      border: 2rpx solid #ea4350;
      border-radius: 45rpx;
      width: 303rpx;
      height: 89rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #ea4350;
      background: #fff;
    }
  }
  .products_container {
    background: #fff;
    margin: 20rpx;
    .container_title {
      font-weight: bold;
      color: #434343;
      font-size: 26rpx;
      padding: 17rpx 26rpx;
    }
  }
  .total {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 83rpx;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 27rpx;
    .price_container {
      .title {
        color: #292929;
        font-size: 26rpx;
        margin-right: 10rpx;
      }
      .price {
        font-size: 28rpx;
        color: #ea4350;
      }
    }
    .goToPay {
      width: 152rpx;
      height: 56rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 21rpx;
      color: #fff;
      background-color: #ea4350;
      border-radius: 26rpx;
    }
    .goToPay.disable {
      background-color: #b6b6b6;
    }
  }
}
</style>